package com.shuai.adapter;

import android.content.Context;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.drawable.ColorDrawable;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.shuai.model.TaskListItem;
import com.shuai.stickynote.R;
import com.shuai.stickynote.TaskNote;
import com.shuai.tool.IDManager;

import java.util.ArrayList;

public class TaskEditListAdapter extends BaseAdapter {
    private Context context;
    private ArrayList<TaskListItem> data;
    private MyViewHolder theLastHolder;
    private ArrayList<TaskNote> taskNodes_new, taskNodes_update, taskNotes;
    private ArrayList<String> taskNodes_delete;
    private String bak = "";
    private ArrayList<MyViewHolder> holderMap;
    private static final String TAG = "fuck";
    private String type = TaskNote.TYPE_SPOT;
    private String group = "";

    public TaskEditListAdapter(Context context) {
        this.context = context;
        this.data = new ArrayList<>();
        this.taskNodes_new = new ArrayList<>();
        this.taskNodes_update = new ArrayList<>();
        this.taskNodes_delete = new ArrayList<>();
    }
//    添加新节点
    public void addNewNote(TaskListItem note){
        if (this.data == null) this.data = new ArrayList<>();
        if (note != null) this.data.add(note);
        notifyDataSetChanged();
    }
//    添加目标任务
    public void addTask(ArrayList<TaskNote> tasks){
        if (tasks == null) return;
        if (this.data == null) this.data = new ArrayList<>();
        if (this.holderMap == null) this.holderMap = new ArrayList<>();
        if (this.taskNodes_update == null) this.taskNodes_update = new ArrayList<>();
        data.clear();
        holderMap.clear();
        this.type = tasks.get(0).getTagType();
        this.group = tasks.get(0).getGroup();
        for (TaskNote note : tasks) {
            data.add(new TaskListItem(note.getContent(),note.getId(),
                    note.getComplete() == 1));
        }
        notifyDataSetChanged();
    }
//    创建新节点对象
    public TaskListItem getNewNote(){
        return new TaskListItem("",true,false,false);
    }
    @Override
    public int getCount() {
        return data.size();
    }
    @Override
    public Object getItem(int position) {
        return data.get(position);
    }
    @Override
    public long getItemId(int position) {
        return position;
    }
    @Override
    public View getView(final int position, View convertView, final ViewGroup parent) {
        if (holderMap == null) holderMap = new ArrayList<>();
        final MyViewHolder holder;
//        实例化holder
        if (convertView == null){
            LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = inflater.inflate(R.layout.item_list_task,null);
            holder = new MyViewHolder();
            holder.et_content = convertView.findViewById(R.id.item_task_et_content);
            holder.iv_add = convertView.findViewById(R.id.item_task_add);
            holder.cb_complete = convertView.findViewById(R.id.item_task_check);
            holder.v_bar = convertView.findViewById(R.id.item_task_bar);
            holder.iv_delete = convertView.findViewById(R.id.item_task_delete);
            holder.et_content.requestFocus();
            holderMap.add(holder);
            convertView.setTag(holder);
        }else {
            holder = (MyViewHolder) convertView.getTag();
            holder.et_content.requestFocus();
            holder.et_content.setSelection(holder.et_content.getText().length());
        }
        if ((data.size()-1) == position) theLastHolder = holder;
//        设置文本
        holder.et_content.setText(data.get(position).getContent());
//        新旧节点样式
        if (!data.get(position).isNewNote()){
            holder.iv_add.setVisibility(View.GONE);
            holder.cb_complete.setVisibility(View.VISIBLE);
            holder.v_bar.setVisibility(View.VISIBLE);
            holder.iv_delete.setVisibility(View.VISIBLE);
            if (type.equals(TaskNote.TYPE_SPOT)){
                holder.cb_complete.setText("●");
            }
            if (type.equals(TaskNote.TYPE_NUM)){
                holder.cb_complete.setText((position+1)+".");
                holder.cb_complete.setTextColor(Color.BLACK);
                holder.cb_complete.setTextSize(20);
            }
        }else {
            holder.iv_add.setVisibility(View.VISIBLE);
            holder.cb_complete.setVisibility(View.GONE);
            holder.v_bar.setVisibility(View.GONE);
            holder.iv_delete.setVisibility(View.GONE);
        }
//        是否画中划线
        if (data.get(position).isComplete())
            holder.complete = 1;
        else holder.complete = 0;
        if (holder.getComplete() == 1)
            holder.et_content.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);
        else holder.et_content.getPaint().setFlags(0);
//        添加按钮事件
        holder.iv_add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!holder.et_content.getText().toString().equals("") && data.get(position).isNewNote()){
                    data.get(position).setNewNote(false);
                    data.get(position).setChange(true);
                    data.get(position).setContent(holder.et_content.getText().toString());
                    addNewNote(getNewNote());
                    holder.et_content.clearFocus();
                }
            }
        });
//        回车事件
        holder.et_content.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (!holder.et_content.getText().toString().equals("") && data.get(position).isNewNote()){
                    data.get(position).setNewNote(false);
                    data.get(position).setChange(true);
                    data.get(position).setContent(holder.et_content.getText().toString());
                    addNewNote(getNewNote());
                    holder.et_content.clearFocus();
                }
                return true;
            }
        });
//        删除按钮事件
        holder.iv_delete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String taskId = data.get(position).getTaskId();
                if (!taskId.equals("")) taskNodes_delete.add(data.get(position).getTaskId());
                data.get(data.size()-1).setContent(theLastHolder.et_content.getText().toString());
                data.get(data.size()-1).setChange(true);
                data.remove(position);
                notifyDataSetChanged();
            }
        });
//        完成按钮
        holder.cb_complete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                holder.setComplete(holder.getComplete() == 0 ? 1 : 0);
                data.get(position).setComplete(!data.get(position).isComplete());
                data.get(data.size()-1).setContent(holderMap.get(data.size()-1).et_content.getText().toString());
                notifyDataSetChanged();
            }
        });
        holder.cb_complete.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                showPopupWindow(holder.cb_complete);
                return true;
            }
        });
        return convertView;
    }
//    获取所有节点数据
    public boolean sortTaskData(String title) {
        if (taskNodes_new == null) taskNodes_new = new ArrayList<>();
        if (group.equals("")) group = IDManager.getID();
        for (int i = 0; i < data.size(); i++) {
            String id = data.get(i).getTaskId();
            String content = holderMap.get(i).et_content.getText().toString();
            int complete = holderMap.get(i).getComplete();
            if (!content.equals("")) {
                if (!id.equals(""))
                    taskNodes_update.add(new TaskNote(id,title,content,group,type,complete));
                else taskNodes_new.add(new TaskNote(title,content,group,type,complete));
            }
        }
        if (taskNodes_update.size() > 0 || taskNodes_new.size() > 0 ) return false;
        return true;
    }

    public ArrayList<TaskNote> getTaskNodes_new() {
        return taskNodes_new;
    }
    public ArrayList<TaskNote> getTaskNodes_update() {
        return taskNodes_update;
    }
    public ArrayList<String> getTaskNodes_delete() {
        return taskNodes_delete;
    }
    //    新节点是否有内容
    public boolean isNewNodeHaveText() {
        return !bak.equals("");
    }
//    显示popupwindow
    private void showPopupWindow(View anchor){
        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View view = inflater.inflate(R.layout.popup_task_edit_type,null);
        final PopupWindow popupWindow = new PopupWindow(view,ViewGroup.LayoutParams.WRAP_CONTENT,
                ViewGroup.LayoutParams.WRAP_CONTENT,true);
        popupWindow.setBackgroundDrawable(new ColorDrawable(Color.WHITE));
        popupWindow.setOutsideTouchable(true);
        popupWindow.setTouchable(true);
        popupWindow.showAsDropDown(anchor,0,0, Gravity.BOTTOM);
        TextView btn_type1 = view.findViewById(R.id.popup_window_task_edit_type1);
        TextView btn_type2 = view.findViewById(R.id.popup_window_task_edit_type2);
        btn_type1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                type = TaskNote.TYPE_SPOT;
                popupWindow.dismiss();
                notifyDataSetChanged();
            }
        });
        btn_type2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                type = TaskNote.TYPE_NUM;
                popupWindow.dismiss();
                notifyDataSetChanged();
            }
        });
    }
//    静态类viewholder,缓存view以提高性能
    static class MyViewHolder{
        public EditText et_content;
        public View v_bar;
        public TextView cb_complete;
        public ImageView iv_add, iv_delete;
        int complete = 0;
        public boolean isTheLast = true;

        public int getComplete() {
            return complete;
        }

        public void setComplete(int complete) {
            this.complete = complete;
        }
    }
}
